
namespace graver
{
    /// <summary>
    /// 计算器
    /// </summary>
    public class Evaluator
    {
        private readonly ExpressionSyntaxNode root;


        public Evaluator(ExpressionSyntaxNode root)
        {
            this.root = root;
        }

        /// <summary>
        /// 计算器入口
        /// </summary>
        /// <returns>计算结果</returns>
        public int Evaluate()
        {
            return EvaluateExpression(root);
        }

        /// <summary>
        /// 实际的计算器入口
        /// </summary>
        /// <param name="root">语法树根节点</param>
        /// <returns>计算结果</returns>
        private int EvaluateExpression(ExpressionSyntaxNode root)
        {
            if (root is NumberExpressionSyntaxNode n)
            {
                return (int)n.NumberToken.Value;
            }
            if (root is BinaryExpressionSyntax bin)
            {
                var left = EvaluateExpression(bin.Left);
                var right = EvaluateExpression(bin.Right);

                switch (bin.OperatorToken.Kind)
                {
                    case SyntaxKind.PlusToken:
                        {
                            return left + right;
                        }
                    case SyntaxKind.MinusToken:
                        {
                            return left - right;
                        }
                    case SyntaxKind.StarToken:
                        {
                            return left * right;
                        }
                    case SyntaxKind.SlashToken:
                        {
                            return left / right;
                        }
                }
                throw new Exception($"Unexpected binary operator {bin.OperatorToken.Kind}");
            }

            if (root is ParenthesizedExpressionSyntax p)
            {
                return EvaluateExpression(p.Expression);
            }

            throw new Exception($"Unexpected node {root.Kind}");
        }

    }
}




